<?php
class MsepCore_Api_Settings extends Core_Api_Abstract {
	
	protected $_settings;
	
	protected $_plugin;
	
	public function __construct() {
		$this->_loadSettings ();
	}
	
	public function __get($key) {
		if ($this->isPlugin ( $key )) {
			$this->_plugin = $key;
			
			return $this;
		}
		
		return $this->getSetting ( $key );
	}
	
	protected function _loadSettings() {
		$table = $this->api ()->getDbtable ( 'settings', 'MsepCore' );
		$rowset = $table->fetchAll ()->toArray ();
		
		$settings = array ();
		
		foreach ( $rowset as $row ) {
			$parts = explode ( ".", $row ['name'] );
			$plugin = $parts [0];
			$name = preg_replace ( "/^{$plugin}_/", "", implode ( "_", $parts ) );
			
			$settings [$plugin] [$name] = $row ['value'];
		}
		
		$settings_obj = array ();
		
		foreach ( $settings as $key => $value ) {
			$settings_obj [$key] = new Zend_Config ( $settings [$key], true );
		}
		
		$this->_settings = new Zend_Config ( $settings_obj, true );
	}
	
	public function isPlugin($plugin) {
		if (is_object ( $this->_settings->$plugin ))
			return true;
		
		return false;
	}
	
	public function getSetting($key) {
		return (isset ( $this->_settings->{$this->_plugin}->$key ) ? $this->_settings->{$this->_plugin}->$key : null);
	}
	
	public function updateFromArray($table, $settings) {
		foreach ( $settings as $key => $value ) {
			$table->update ( array ('value' => $value ), "name = '" . str_replace ( "_", ".", $key ) . "'" );
		}
	}

}